package org.example.util;

import java.io.*;

public class WindowsDnsManager {
    // 设置 IPv4 手动 DNS
    public static void setManualDNSv4(String interfaceName, String primaryDNS) throws IOException {
        String cmd = String.format("netsh interface ip set dns name=\"%s\" static %s", interfaceName, primaryDNS);
        executeCommand(cmd);
    }

    // 设置 IPv4 自动获取 DNS
    public static void setAutoDNSv4(String interfaceName) throws IOException {
        String cmd = String.format("netsh interface ip set dns name=\"%s\" source=dhcp", interfaceName);
        executeCommand(cmd);
    }

    // 设置 IPv6 手动 DNS
    public static void setManualDNSv6(String interfaceName, String primaryDNSv6) throws IOException {
        // 注意参数顺序：source=static 后必须跟 address=
        String cmd = String.format(
                "netsh interface ipv6 set dnsservers name=\"%s\" source=static address=%s validate=no",
                interfaceName,
                primaryDNSv6
        );
        executeCommand(cmd);
    }

    // 设置 IPv6 自动获取 DNS
    public static void setAutoDNSv6(String interfaceName) throws IOException {
        String cmd = String.format(
                "netsh interface ipv6 set dnsservers name=\"%s\" source=dhcp",
                interfaceName
        );
        executeCommand(cmd);
    }

    // 刷新dns
    public static void flushDns() throws IOException {
        String cmd = "ipconfig /flushdns";
        executeCommand(cmd);
    }

    // 执行系统命令并打印输出
    private static void executeCommand(String command) throws IOException {
        Process process = Runtime.getRuntime().exec(command);

        try (
                BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
                BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()))
        ) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            while ((line = errorReader.readLine()) != null) {
                System.err.println(line);
            }
        }
    }
}
